<template>
  <div>
    <el-col :span="24">
      <basic-container v-loading="loading">
        <el-collapse>
          <div class="card-header">
            <h3>
              {{ title }}
            </h3>
          </div>
          <template>
            <div class="container">
              <div class="left-section">
                <el-card>
                  <div class="card-content">
                    <div class="card-header">
                      <span class="section-title">餐食概况：</span>
                    </div>
                    <div class="card-content">
                      <div class="section">
                        <span class="section-title">中式A餐：</span>

                        <el-tag
                          :key="index"
                          v-for="(item, index) in dateData.lunchYYFoodList"
                        >
                          {{ item.name }}
                        </el-tag>
                        <el-tag
                          v-if="
                            dateData.lunchYYFoodList &&
                            dateData.lunchYYFoodList.length === 0
                          "
                          type="danger"
                        >
                          未配置
                        </el-tag>
                        <span style="float: right"
                        >{{ dateData.lunchYYCount || 0 }}份</span
                        >
                      </div>
                      <div class="section">
                        <span class="section-title">中式B餐：</span>

                        <el-tag
                          :key="index"
                          v-for="(item, index) in dateData.dinerYYFoodList"
                        >
                          {{ item.name }}
                        </el-tag>
                        <el-tag
                          v-if="
                            dateData.dinerYYFoodList &&
                            dateData.dinerYYFoodList.length === 0
                          "
                          type="danger"
                        >
                          未配置
                        </el-tag>
                        <span style="float: right"
                        >{{ dateData.dinerYYCount || 0 }}份</span
                        >
                      </div>
                      <div class="section">
                        <span class="section-title">西式C餐：</span>

                        <el-tag
                          :key="index"
                          v-for="(item, index) in dateData.lunchJZFoodList"
                        >
                          {{ item.name }}
                        </el-tag>
                        <el-tag
                          v-if="
                            dateData.lunchJZFoodList &&
                            dateData.lunchJZFoodList.length === 0
                          "
                          type="danger"
                        >
                          未配置
                        </el-tag>
                        <span style="float: right"
                        >{{ dateData.lunchJZCount || 0 }}份</span
                        >
                      </div>
                      <div class="section">
                        <span class="section-title">西式D餐：</span>

                        <el-tag
                          :key="index"
                          v-for="(item, index) in dateData.dinerJZFoodList"
                        >
                          {{ item.name }}
                        </el-tag>
                        <el-tag
                          v-if="
                            dateData.dinerJZFoodList &&
                            dateData.dinerJZFoodList.length === 0
                          "
                          type="danger"
                        >
                          未配置
                        </el-tag>
                        <span style="float: right"
                        >{{ dateData.dinerJZCount || 0 }}份</span
                        >
                      </div>
                    </div>

                    <div class="section">
                      <span class="section-title">个性餐份数：</span>
                      <span>{{ dateData.specCount }}份</span>
                      <el-button
                        style="margin-left: 12px"
                        type="primary"
                        icon="el-icon-search"
                        size="small"
                        @click="openSpec(1)"
                        circle
                      ></el-button>
                    </div>
                    <div class="section">
                      <span class="section-title">加饭份数：</span>
                      <span>{{ dateData.addMealCount }}份</span>
                    </div>
                    <div class="section">
                      <span class="section-title">忌口香菜份数：</span>
                      <span>{{ dateData.notCorianderCount }}份</span>
                    </div>
                    <div class="section">
                      <span class="section-title">特殊时间份数：</span>
                      <span>{{ dateData.specTimeCookbookList.length }}份</span>
                      <el-button
                        style="margin-left: 12px"
                        type="primary"
                        icon="el-icon-search"
                        size="small"
                        @click="openSpecTime"
                        circle
                      ></el-button>
                    </div>
                  </div>
                </el-card>
              </div>

              <div class="right-section">
                <div
                  style="
                    margin: 10px 40px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <el-switch
                    style="display: block"
                    v-model="isCP"
                    active-color="#13ce66"
                    inactive-color="#409EFF"
                    active-text="按菜品统计"
                    inactive-text="按食材统计"
                  >
                  </el-switch>
                  <el-select v-model="searchMeal"
                             placeholder="A餐或B餐"
                             style="width: 200px !important; height: 32px; line-height: 32px;"
                             clearable
                             @change="searchMealChange"
                  >
                    <el-option
                      v-for="item in mealOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>

                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-takeaway-box"
                    @click='exportTable'
                  >导出图片
                  </el-button
                  >
                </div>
                <el-card>
                  <div v-if='isCP' class="card-content">
                    <el-table
                      id='tablePrint'
                      :data="foodStaticsList"
                      :height="tableHeight"
                    >
                      <el-table-column
                        prop="name"
                        label="菜品名称"
                      ></el-table-column>
                      <el-table-column
                        prop="count"
                        label="数量"
                      ></el-table-column>
                    </el-table>
                  </div>
                  <div v-if='!isCP' class="card-content">
                    <el-table
                      id='tablePrint'
                      :data="grams"
                      :height="tableHeight"
                    >
                      <el-table-column
                        prop="ingredientsName"
                        label="食材名称"
                      ></el-table-column>
                      <el-table-column
                        prop="grams"
                        label="克重/g"
                      ></el-table-column>
                      <el-table-column
                        prop="ingredientsUnit"
                        label="份数"
                      >
                        <template slot-scope="scope">
                          <el-tag v-if="scope.row.ingredientsUnit && scope.row.ingredientsUnit !== '' && ingredientsUnit(scope.row)">{{ `${(scope.row.grams / ingredientsUnit(scope.row).grams).toFixed(2)} ${ingredientsUnit(scope.row).name}` }}</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="jin"
                        label="市斤"
                      ></el-table-column>
                      <el-table-column
                        prop="price"
                        label="食材成本"
                      ></el-table-column>
                    </el-table>
                    <div style="float: right; margin-right: 20px; margin-top: 20px">总成本: <span>{{
                        totalPrice.toFixed(2)
                      }}</span></div>
                  </div>
                </el-card>
              </div>
            </div>
          </template>
        </el-collapse>
      </basic-container>
    </el-col>
    <el-drawer size="70%" :visible.sync="drawerVisible" title="会员菜品列表">
      <el-row>
        <el-col :span="24">
          <el-card shadow="always">
            <span style="color: #2d8cf0; margin-left: 5px">{{ `全粗粮 ${coarseCount(meal)} 份; 全白米 ${riceCount(meal)} 份 -- 全粗粮补正: ${(coarseCount(meal) - riceCount(meal)) * 20}g；全白米补正: ${(riceCount(meal) - coarseCount(meal)) * 40}g；` }}</span>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-takeaway-box"
              style="float: right; margin-right: 20px; margin-bottom: 20px"
              @click='exportSpecTable'
            >导出图片
            </el-button>
            <el-table
              :height="tableHeightDrawer"
              id="specTable"
              :data="tableData(meal)"
              row-key="foodsStr"
              :cell-style="cellStyle"
              :expand-row-keys="expandRowKeys"
              :default-expand-all="false">
              <el-table-column prop="foodItems" label="菜品" min-width="300">
                <template slot-scope="scope">
                  <div>
              <span v-for="(food, _index) in scope.row.foodItems" :key="_index">
                {{ _index === 0 ? food.foodName : ` + ${food.foodName}` }}
              </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="count"
                label="数量"
              ></el-table-column>
              <el-table-column
                prop="statics"
                label="主食份数小计"
                min-width="200"
              ></el-table-column>
              <el-table-column type="expand" width="250">
                <template slot="header" slot-scope="scope">
                  <el-switch
                    v-model="expendAll"
                    active-text="全部展开"
                    @change="expendAllChange"
                    inactive-text="">
                  </el-switch>
                </template>
                <template slot-scope="props">
                  <el-row v-for="(item, itemIndex) in props.row.subList" :key="itemIndex" style="margin-bottom: 10px">
                    <el-col span="5">会员:
                      <el-tag>{{ item.memberName ? item.memberName : '无' }}</el-tag>
                    </el-col>
                    <el-col span="5">主食类型:
                      <el-tag type="success" style="font-size: 16px" v-if="item.mainCourseType">{{item.mainCourseType }}</el-tag>
                      <el-tag type="info" v-else>默认</el-tag>
                    </el-col>
                    <el-col span="5">备注:
                      <el-tag type="success" v-if="item.remark">{{item.remark }}</el-tag>
                      <el-tag type="info" v-else>无</el-tag>
                    </el-col>
                    <el-col span="5">其他备注:
                      <el-tag type="success" v-if="item.remark1">{{item.remark1 }}</el-tag>
                      <el-tag type="info" v-else>无</el-tag>
                    </el-col>
                  </el-row>
                  <!--                  <el-table :height="tableHeightDrawer" :data="props.row.subList">-->
                  <!--                    <el-table-column-->
                  <!--                      prop="memberName"-->
                  <!--                      label="会员"-->
                  <!--                    ></el-table-column>-->
                  <!--                    <el-table-column-->
                  <!--                      prop="mainCourseType"-->
                  <!--                      label="主食类型"-->
                  <!--                    ></el-table-column>-->
                  <!--                    <el-table-column-->
                  <!--                      prop="remark"-->
                  <!--                      label="备注"-->
                  <!--                    ></el-table-column>-->
                  <!--                    <el-table-column-->
                  <!--                      prop="remark1"-->
                  <!--                      label="其他备注"-->
                  <!--                    ></el-table-column>-->
                  <!--                  </el-table>-->
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-card shadow="always">
            <div slot="header" class="clearfix">
              <span>荤菜统计</span>
            </div>
            <el-table
              id='tablePrint'
              :data="foodTableData(1)"
              :height="tableHeightDrawer"
            >
              <el-table-column
                prop="name"
                label="菜品名称"
              ></el-table-column>
              <el-table-column
                prop="count"
                label="数量"
              ></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="always">
            <div slot="header" class="clearfix">
              <span>素菜统计</span>
            </div>
            <el-table
              id='tablePrint'
              :data="foodTableData(2)"
              :height="tableHeightDrawer"
            >
              <el-table-column
                prop="name"
                label="菜品名称"
              ></el-table-column>
              <el-table-column
                prop="count"
                label="数量"
              ></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="always">
            <div slot="header" class="clearfix">
              <span>主食统计</span>
            </div>
            <el-table
              id='tablePrint'
              :data="foodTableData(3)"
              :height="tableHeightDrawer"
            >
              <el-table-column
                prop="name"
                label="菜品名称"
              ></el-table-column>
              <el-table-column
                prop="count"
                label="数量"
              ></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-drawer>
    <el-drawer size="70%" :visible.sync="drawerSpecTimeVisible" title="特殊时段列表">
      <el-table
        id='tablePrint'
        :data="specTimeRangeCookbookData"
        :height="tableHeight"
      >
        <el-table-column
          prop="receiver"
          label="客户"
        ></el-table-column>
        <el-table-column prop="foodItems" label="菜品" min-width="100">
          <template slot-scope="scope">
            <div>
              <span v-for="(food, _index) in scope.row.foodItems" :key="_index">
                {{ _index === 0 ? food.foodName : ` + ${food.foodName}` }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
        >
          <template slot-scope="scope">
            <el-tag
              type="primary"
              disable-transitions>{{scope.row.address}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="timeRange"
          label="时间段"
        >
          <template slot-scope="scope">
            <el-tag
              type="primary"
              disable-transitions>{{scope.row.timeRange.replace(',', ' ~ ')}}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {dateFormat} from "@/util/date";
import {staticsDate} from "@/api/member/member_cookbook";
import html2canvas from 'html2canvas';
import {computeFoodsCount, sortFoods} from "@/util/food";

export default {
  name: "staticsCar",
  props: {
    date: {
      type: Date,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      logActiveNames: ["26"],
      dateData: {},
      grams: [],
      foodStaticsList: [],
      tomorrowData: {},
      tomorroGrams: [],
      tableHeight: Math.floor(window.innerHeight / 2),
      showToday: true,
      drawerVisible: false,
      drawerSpecTimeVisible: false,
      meal: 1,
      tableHeightDrawer: Math.floor(window.innerHeight * 0.4),
      isCP: true,
      tomorrowTotalPrice: 0,
      totalPrice: 0,
      expendAll: false,
      expandRowKeys: [],
      searchMeal: '',
      mealOptions: [
        {
          value: '',
          label: '默认'
        },
        {
          value: 1,
          label: 'A餐'
        }, {
          value: 2,
          label: 'B餐'
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '后天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', date)
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 2)
            picker.$emit('pick', date);
          }
        }, {
          text: '今天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date);
          }
        }, {
          text: '昨天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '前天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }]
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    ingredientsUnit() {
      return (row) => {
        try {
          return JSON.parse(row.ingredientsUnit)
        } catch (e) {
          return ''
        }
      }
    },
    coarseCount() {
      return (meal) => {
        let count = 0
        this.tableData(meal).forEach(item => {
          item.subList.forEach(subItem => {
            if (subItem.mainCourseType.includes('全粗粮')) {
              count++
            }
          })
        })
        return count
      }
    },
    riceCount() {
      return (meal) => {
        let count = 0
        this.tableData(meal).forEach(item => {
          item.subList.forEach(subItem => {
            if (subItem.mainCourseType.includes('全白米')) {
              count++
            }
          })
        })
        return count
      }
    },
    tableData() {
      return () => {
        let dayData = this.dateData
        const specCookbookList = dayData.specCookbookList

        const list = []
        specCookbookList.map((item) => {
          const foodItems = this.formatFoodItem(item)
          const foodsStr = foodItems.map(foodItem => foodItem.name).join('+')
          const foodsStrList = list.map((e) => e.foodsStr)
          const subItem = {
            memberName: item.memberName,
            foodItems: this.formatFoodItem(item),
            remark: item.remark,
            remark1: item.remark1,
            mainCourseType: item.mainCourseType,
          }
          if (!foodsStrList.includes(foodsStr)) {
            list.push({
              foodsStr: foodsStr,
              foodFirstName: foodItems[0] ? foodItems[0].name : '菜品已删除',
              foodItems: this.formatFoodItem(item),
              subList: [
                subItem
              ],
              count: 1,
            })
          } else {
            list.forEach(e => {
              if (e.foodsStr === foodsStr) {
                e.subList.push(subItem)
                e.count += 1
              }
            })
          }
        })

        list.forEach(item => {
          let subList = item.subList
          let mainCourseCount1 = 0
          let mainCourseCount2 = 0
          let mainCourseCount3 = 0
          subList.forEach(subItem => {
            if (subItem.mainCourseType === '全白米') {
              mainCourseCount1 += 1
            } else if (subItem.mainCourseType.includes('全粗粮')) {
              mainCourseCount2 += 1
            } else if (!subItem.mainCourseType || subItem.mainCourseType === '' || subItem.mainCourseType === '默认') {
              mainCourseCount3 += 1
            }
          })
          item.statics = ''
          if (mainCourseCount2 !== 0) {
            item.statics = `全粗粮 ${mainCourseCount2} 份；`
          }
          if (mainCourseCount1 !== 0) {
            item.statics = `${item.statics}全白米 ${mainCourseCount1} 份；`
          }
          if (mainCourseCount3 !== 0) {
            item.statics = `${item.statics}默认 ${mainCourseCount3} 份；`
          }
        })

        list.sort(function (a, b) {
          return b.count - a.count
        })

        list.sort(function (a, b) {
          return a.foodFirstName.length - b.foodFirstName.length
        })

        return list
      }
    },
    foodTableData() {
      return (type) => {
        const foods = []
        const list = this.dateData.specCookbookList
        list.map(item => {
          const foodItems = this.formatFoodItem(item)
          computeFoodsCount(foods, foodItems, type)
        })
        return foods
      }
    },
    specTimeRangeCookbookData() {
      let list = this.dateData.specTimeCookbookList
      list = list.map((item) => {
        item.foodItems = this.formatFoodItem(item)
        return item
      })
      return list
    },
    formatFoodItem() {
      return (item) => {
        try {
          const foodItems = JSON.parse(item.foods)
          return sortFoods(foodItems);
        } catch (e) {
          return [];
        }
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    openSpec(meal) {
      this.meal = meal
      this.drawerVisible = true
    },
    openSpecTime() {
      this.drawerSpecTimeVisible = true
    },
    cellStyle ({row, column, rowIndex, columnIndex}){
      return {
        'font-weight': 'blod',
        'font-size': '16px'
      }
    },
    searchMealChange(meal) {
      const params = {
        date: dateFormat(this.date),
        meal: meal,
      }
      this.loading = true
      staticsDate(params).then((res) => {
        this.checkData(res.data.data)
        this.loading = false
      })
    },
    expendAllChange(val) {
      if (val) {
        this.expandRowKeys = this.tableData(this.meal).map((item) => {
          return item.foodsStr
        })
      } else {
        this.expandRowKeys = []
      }
    },
    generateFoodItems(item) {
      const foodItems = [];
      const formattedFoodItems = this.formatFoodItem(item);

      const foodNames = formattedFoodItems.map((food, foodIndex) => {
        return foodIndex === 0 ? food.foodName : ` + ${food.foodName}`;
      });

      foodItems.push(foodNames.join(""));

      return foodItems.join("");
    },
    handleChange(val) {
      console.log(val);
    },
    handleSearch() {
      const params = {
        date: dateFormat(this.date),
      }
      this.loading = true
      staticsDate(params).then((res) => {
        this.dateData = res.data.data
        this.checkData(res.data.data)
        this.loading = false
      })
    },
    init() {
      this.handleSearch()
    },
    checkData(data) {
      this.foodStaticsList = data.foodStaticsList
      let {foodStaticsList} = data;
      // 食材成本核算
      let foosGrams = [];
      // 食材成本核算逻辑
      foodStaticsList.map((item) => {
        item.item.foodIngredientsList.map((food) => {
          let INDEX = foosGrams.findIndex((i) => food.ingredientsId == i.ingredientsId);
          if (INDEX != -1) {
            foosGrams[INDEX]["grams"] += food.grams * item.count;
            const price = (foosGrams[INDEX]["grams"] / 1000) * food.ingredientsPrice
            foosGrams[INDEX]["price"] = price.toFixed(2)
            foosGrams[INDEX]["priceFloat"] = price
          } else {
            food.grams = food.grams * item.count;
            const price = (food.grams / 1000) * food.ingredientsPrice
            food.priceFloat = price
            food.price = price.toFixed(2)
            foosGrams.push(food);
          }
        });
      });
      let totalPrice = 0
      foosGrams.forEach(ele => {
        ele.jin = (ele.grams * 0.002).toFixed(2)
        totalPrice += ele.priceFloat
      })
      this.grams = foosGrams
      this.totalPrice = totalPrice
    },
    showDrawer() {
      this.drawerVisible = true;
    },
    exportTable() {
      const that = this
      this.tableHeight = ''
      this.$nextTick(() => {
        // const table = this.$refs.tablePrint;
        let table = document.getElementById('tablePrint')
        html2canvas(table).then((canvas) => {
          const dataURL = canvas.toDataURL('image/png');
          const link = document.createElement('a');
          link.href = dataURL;
          link.download = '统计.png';
          link.click();

          that.tableHeight = Math.floor(window.innerHeight / 2)
        });
      });
    },
    exportSpecTable() {
      const that = this
      this.tableHeightDrawer = ''
      this.$nextTick(() => {
        let table = document.getElementById('specTable')
        html2canvas(table).then((canvas) => {
          const dataURL = canvas.toDataURL('image/png');
          const link = document.createElement('a');
          link.href = dataURL;
          link.download = '个性餐列表.png';
          link.click();

          that.tableHeightDrawer = Math.floor(window.innerHeight / 2)
        });
      });
    },
  },
};
</script>

<style scoped>
.el-divider--horizontal {
  margin: 12px 0 !important;
}

.el-font-size {
  font-size: 14px;
}
</style>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
}

.left-section,
.right-section {
  width: 45%;
}

.card-header {
  background-color: #f5f7fa;
  padding: 10px;
  text-align: center;
}

.change-btn {
  color: #ecf5ff;
}

.card-content {
  padding: 20px;
}

.section {
  margin-bottom: 10px;
}

.section-title {
  font-weight: bold;
}

.el-tag {
  margin-right: 5px;
}
</style>
